using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Script.Serialization;
using Medora.Model;
using Medora.Model.Basic;
using Medora.Model.Institutions;
using Medora.Services;

namespace Medora.Web.App_Code
{
    public class ControllerBase<T, F> : BaseApiController where T: DeletedEntity where F: IFilter
    {
        protected IService<T, F> _service;
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        // GET api/<controller>
        public ControllerBase(IService<T, F> service)
        {
            _service = service;
        }

        [ActionName("GetByPage")]
        public IPagedEntities<T> GetByPage(int pageSize, int page, string filter, string ss)
        {
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                var filterObj = serializer.Deserialize<F>(filter);
                SortInfo sort = null;
                if (!string.IsNullOrEmpty(ss)) sort = serializer.Deserialize<SortInfo>(ss);
                return _service.GetPaged(pageSize, page, filterObj, sort);
            }
            return null;
        }

        [ActionName("GetCount")]
        public int GetCount()
        {
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                return _service.GetCount();
            }
            return 0;
        }

        // GET api/<controller>/5
        public string Get(Guid id)
        {
            return "value";
        }

        // POST api/<controller>
        public HttpResponseMessage Post([FromBody]T value)
        {
            if (ModelState.IsValid)
            {
                var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
                if (user != null && user.ProviderUserKey != null)
                {
                    Guid userId = (Guid)user.ProviderUserKey;
                    if (_service.Save(userId, value)) return Request.CreateResponse(HttpStatusCode.OK, value);
                }
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please sign in!");
            }
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Validation error");
        }

        // DELETE api/<controller>/5
        [HttpDelete]
        public void Delete(string id)
        {
            var ids = serializer.Deserialize<List<Guid>>(id);
            if (_service.Delete(ids)) Request.CreateResponse(HttpStatusCode.OK);

        }
        
    }
}